package com.cxyzy.demo;

import android.Manifest;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.widget.ImageView;
import android.widget.Toast;

import com.jakewharton.rxbinding2.view.RxView;
import com.tbruyelle.rxpermissions2.RxPermissions;

import java.io.IOException;

import butterknife.BindView;
import butterknife.ButterKnife;

public class MainActivity extends AppCompatActivity {

    private static final int REQUEST_CODE_GALLERY = 0x10;// 图库选取图片标识请求码

    @BindView(R.id.iv_pic)
    ImageView picIv;// imageView控件
    private final RxPermissions rxPermissions = new RxPermissions(this);

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);// 控件绑定
        RxView.clicks(findViewById(R.id.btn_gallery))
                .compose(rxPermissions.ensure(Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE))
                .subscribe(granted -> {
                    if (granted) {
                        selectPicture();
                    } else {
                        Toast.makeText(this, "需要相机和存储权限", Toast.LENGTH_SHORT).show();
                    }
                });
    }


    /**
     * 图库选择图片
     */
    private void selectPicture() {
        Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(intent, REQUEST_CODE_GALLERY);
    }

    /**
     * 接收#startActivityForResult(Intent, int)调用的结果
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK && requestCode == REQUEST_CODE_GALLERY) {
            Uri pictureUri = data.getData();
            try {
                Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(),pictureUri);
                BitmapUtils.compress(bitmap,1024);
                displayPicture(bitmap);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 显示图片
     * @param imageUri 图片的uri
     */
    private void displayPicture(Uri imageUri) {
        picIv.setImageURI(imageUri);
    }
    private void displayPicture(Bitmap bitmap) {
        picIv.setImageBitmap(bitmap);
    }

}